import base from '../../services/apis/baseService'
// import {isPhoneAvailable, isNumberStr} from '../../plugins/util'
import {Message} from 'element-ui'
import config from '../../config'
import storage from '../../plugins/storage'

const state = {
  token: '',
  // 登陆用户信息
  userInfo: {},
  // 用户详细信息
  userInfoDetail: {}
}

// getters
const getters = {}

// actions
const actions = {
  /**
   * 登录
   */
  login ({commit, state}, data) {
    return new Promise((resolve, reject) => {
      // 表单验证
      if (!data.username) {
        Message({
          message: '请输入用户名',
          type: 'warning'
        })
        return false
      }
      if (!data.password) {
        Message({
          message: '请输入密码',
          type: 'warning'
        })
        return false
      }
      // 登录
      base.login(data.username, data.password).then(function (res) {
        commit('setToken', res.data.token)
        commit('setUserInfo', {
          name: res.data.name,
          deptname: res.data.deptname,
          corpname: res.data.corpname,
          modules: res.data.modules
        })
        resolve()
      })
    })
  },
  /**
   * 获取用户详细信息
   */
  getUserInfoDetail ({commit, state}, data) {
    return new Promise((resolve, reject) => {
      base.getUserInfo().then(function (res) {
        commit('setUserInfoDetail', res.data || {})
        resolve()
      })
    })
  }
}

// mutations
const mutations = {
  // 设置token
  setToken (state, data) {
    state.token = data
    storage.set(config.tokenKeyName, data)
  },
  // 设置用户登陆信息
  setUserInfo (state, data) {
    state.userInfo = data
    storage.set('userInfo', data)
  },
  // 从本地获取用户登录信息
  setUserInfoLocal (state) {
    let res = storage.get('userInfo')
    if (res) {
      state.userInfo = res
    }
  },
  // 设置用户账号信息
  setUserInfoDetail (state, data) {
    state.userInfoDetail = data
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
